<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1, '0')">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button v-if="scope.row.type===1" type="text" @click="addPermission(2, scope.row.id)">添加</el-button>
              <el-button type="text" @click="editPermission(scope.row.id)">编辑</el-button>
              <el-button type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <div>
        <perDialog
          ref="perDialog"
          :pid="pid"
          :show-dialog="showDialog"
          :type="type"
          :is-edit="isEdit"
          :form-data-obj="formData"
          @close="showDialog = false"
          @confirm="confirmFn"
        />
      </div>
    </div>
  </div>
</template>

<script>
import { getPermissionListAPI, addPermissionAPI, getPermissionDetailAPI } from '@/api'
import { transTree } from '@/utils'
import perDialog from './components/perDialog.vue'
export default {
  components: {
    perDialog
  },
  data() {
    return {
      permissionList: [],
      showDialog: false,
      type: 0, // 添加权限-类型
      pid: 0, // 添加权限-pid
      isEdit: false, // 编辑
      formData: {} // 编辑时,获取权限点详情对象
    }
  },
  created() {
    this.getPermissionListFn()
  },
  methods: {
    async getPermissionListFn() {
      const res = await getPermissionListAPI().catch(err => err)
      if (!res.success) return this.$message.error(res.message)
      this.permissionList = transTree(res.data, '0')
    },
    // 添加权限 - 按钮点击事件
    addPermission(type, id) {
      // 控制弹框展示
      this.showDialog = true

      // 记录当前添加的关键信息
      this.type = type
      this.pid = id
    },
    // 确定点击事件
    async confirmFn(data) {
      const res = await addPermissionAPI(data).catch(err => err)
      if (!res.success) return this.$message.error(res.message)
      this.$message.success(res.message)
      // 添加成功
      this.getPermissionListFn()
      this.showDialog = false
    },
    // 编辑 点击事件
    async editPermission(id) {
      this.showDialog = true
      this.isEdit = true
      const res = await getPermissionDetailAPI(id)
      this.formData = res.data
    }
  }
}
</script>

<style lang="scss" scoped></style>
